<script setup lang="ts">
import {Divider, message} from 'ant-design-vue';
import {useForm, z} from '#/ui-kit';

import {useUserStore} from '#/stores';
import {updatePassword} from '#/api/system/user';

const userStore = useUserStore();

const [Form, formApi] = useForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
      allowClear: true,
    },
  },
  layout: 'horizontal',
  actionPosition: 'left',
  schema: [
    {
      label: '原始密码',
      fieldName: 'oldPassword',
      component: 'InputPassword',
      componentProps: {placeholder: '请输入原始密码'},
      rules: 'required',
    },
    {
      label: '新密码',
      fieldName: 'newPassword',
      component: 'InputPassword',
      componentProps: {placeholder: '请输入新密码'},
      rules: z.string({required_error: '请输入新密码'})
          .min(6, '密码长度不能小于6位')
          .max(16, '密码长度不能大于16位'),
    },
    {
      label: '确认密码',
      fieldName: 'confirmPassword',
      component: 'InputPassword',
      componentProps: {placeholder: '请输入确认密码'},
      dependencies: {
        rules({newPassword}) {
          return z.string({required_error: '请输入确认密码'})
              .refine((value) => value === newPassword, {
                message: '两次输入的密码不一致',
              });
        },
        triggerFields: ['newPassword'],
      }
    },
  ],
  handleSubmit: (values) => {
    let userId = userStore?.userInfo?.userId;
    values.userId = userId;
    formApi.setState({submitButtonOptions: {loading: true}});
    updatePassword(values).then(() => {
      message.success('密码修改成功');
      formApi.resetForm();
    }).finally(() => {
      formApi.setState({submitButtonOptions: {loading: false}});
    });
  }
});
</script>

<template>
  <div>
    <header class="h-[38px] leading-[38px] text-sm font-medium">密码设置</header>
    <Divider class="m-0"/>
    <Form class="pt-2 pr-2"/>
  </div>
</template>